//
//  MainViewController.swift
//  V2ex-Swift
//
//  Created by Jasper on 2/28/16.
//  Copyright © 2016 Fin. All rights reserved.
//

import UIKit
import SVProgressHUD
import HMSegmentedControl
import MJRefresh
import UITableView_FDTemplateLayoutCell
import AVOSCloud

fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l <= r
  default:
    return !(rhs < lhs)
  }
}


class MainViewController: RootViewController,UIScrollViewDelegate, MainPageTopicTableViewDelegate {
    
    
    var scrollView: UIScrollView?
    var segmentedControl: HMSegmentedControl?
    
    var newTopicTableView: MainPageTopicTableView?
    var mostReplyTopicTabView: MainPageTopicTableView?
    var mostClickTopicTabView: MainPageTopicTableView?
    var commendTabView: MainPageTopicTableView?
    var newReplyTableView: MainPageReplyTableView?
    
    var dataDic = Dictionary<UITableView,Array<AVObject>>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "主页"
        tabBarController?.tabBar.selectedItem?.selectedImage = UIImage(named: "tabbar_home_selected")
        
        let viewWidth = self.view.frame.width
        segmentedControl = HMSegmentedControl(sectionTitles: ["最新主题", "最多回复", "最多阅读","精华主题", "最新回复"])
        segmentedControl?.frame = CGRect(x: 0, y: 0, width: viewWidth, height: 40)
        segmentedControl?.autoresizingMask = [.flexibleRightMargin,.flexibleWidth]
        segmentedControl?.selectionIndicatorLocation = .down
        segmentedControl?.isVerticalDividerEnabled = false
        
        segmentedControl?.titleFormatter = { (control:HMSegmentedControl?, title:String?, index:UInt, selected:Bool)-> NSAttributedString? in
            var dic: Dictionary<String, AnyObject> = [NSFontAttributeName:UIFont.systemFont(ofSize: 15)]
            if selected {
                dic[NSForegroundColorAttributeName] = UIColor.mainColor()
            } else {
                dic[NSForegroundColorAttributeName] = UIColor.black
            }
            
            let attString = NSAttributedString(string: title!, attributes: dic)
            return attString
        }
        
        segmentedControl?.selectedSegmentIndex = 0
        segmentedControl?.backgroundColor = UIColor.viewBackColor()
        segmentedControl?.selectionIndicatorColor = UIColor.mainColor()
        segmentedControl?.selectionStyle = .box
        segmentedControl?.selectionIndicatorHeight = 1.5
        segmentedControl?.tag = 3
        segmentedControl?.indexChangeBlock = {(index: Int) in
            self.loadTableViewData(index)
            self.scrollView?.scrollRectToVisible(CGRect(x: viewWidth*CGFloat(index), y: 0, width: viewWidth, height: 200), animated: true)
        }
        
         view.addSubview(segmentedControl!)
        
        let height = self.view.frame.height-40-64-44
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: 40, width: viewWidth, height: height))
//        scrollView?.backgroundColor = UIColor.redColor()
        scrollView?.isPagingEnabled = true
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.contentSize = CGSize(width: viewWidth * 5, height: 200)
        scrollView?.delegate = self
        scrollView?.scrollRectToVisible(CGRect(x: 0, y: 0, width: viewWidth, height: 200), animated: true)
        view.addSubview(scrollView!)
        
        newTopicTableView = MainPageTopicTableView(frame: CGRect(x: 0, y: 0, width: viewWidth, height: height), style: .plain)
        newTopicTableView?.requestData(true)
        newTopicTableView?.selectDelegate = self
        newTopicTableView?.topicType = .newTopic
        scrollView?.addSubview(newTopicTableView!)
        
        mostReplyTopicTabView = MainPageTopicTableView(frame: CGRect(x: viewWidth, y: 0, width: viewWidth, height: height), style: .plain)
        mostReplyTopicTabView?.selectDelegate = self
        mostReplyTopicTabView?.topicType = .mostReply
        scrollView?.addSubview(mostReplyTopicTabView!)
        
        mostClickTopicTabView = MainPageTopicTableView(frame: CGRect(x: viewWidth*2, y: 0, width: viewWidth, height: height), style: .plain)
        mostClickTopicTabView?.selectDelegate = self
        mostClickTopicTabView?.topicType = .mostClick
        scrollView?.addSubview(mostClickTopicTabView!)
        
        commendTabView = MainPageTopicTableView(frame: CGRect(x: viewWidth*3, y: 0, width: viewWidth, height: height), style: .plain)
        commendTabView?.selectDelegate = self
        commendTabView?.topicType = .commendTopic
        scrollView?.addSubview(commendTabView!)
        
        newReplyTableView = MainPageReplyTableView(frame: CGRect(x: viewWidth*4, y: 0, width: viewWidth, height: height), style: .plain)
        newReplyTableView?.selectDelegate = self
        scrollView?.addSubview(newReplyTableView!)
    }
    
    func loadTableViewData(_ index: Int) {
        AVAnalytics.event("首页segment:\(index)")
        switch index {
        case 0:
            if self.newTopicTableView?.topicArray.count <= 0 {
                self.newTopicTableView?.requestData(true)
            }
        case 1:
            if self.mostReplyTopicTabView?.topicArray.count <= 0 {
                self.mostReplyTopicTabView?.requestData(true)
            }
        case 2:
            if self.mostClickTopicTabView?.topicArray.count <= 0 {
                self.mostClickTopicTabView?.requestData(true)
            }
        case 3:
            if self.commendTabView?.topicArray.count <= 0 {
                self.commendTabView?.requestData(true)
            }
        case 4:
            if self.newReplyTableView?.replyArray.count <= 0 {
                self.newReplyTableView?.requestData(true)
            }
        default:
            if self.newTopicTableView?.topicArray.count <= 0 {
                self.newTopicTableView?.requestData(true)
            }
        }
    }
    
    // MARK: UIScrollViewDelegate
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageWidth = scrollView.frame.size.width
        let page = scrollView.contentOffset.x / pageWidth
        segmentedControl?.setSelectedSegmentIndex(UInt(page), animated: true)
        self.loadTableViewData(Int(page))
    }
    
    // MARK: MainPageTopicTableViewDelegate
    func mainPageTopicTableView(_ tableView:UITableView, object: AVObject) {
        var reTopic = Topic()
        var reCity = City()
        var orderType = 0
        if let topic = object as? Topic {
            reTopic = topic
            reCity = topic.city!
        } else if let reply = object as? Reply {
            reTopic = reply.topic!
            reCity = reply.city!
            orderType = 1
        }

        let cirDetailVC = UIStoryboard.mainStoryboard.instantiateViewController(withIdentifier: "CirclReplyViewController") as! CirclReplyViewController;
        cirDetailVC.topic = reTopic
        cirDetailVC.city = reCity
        cirDetailVC.orderType = orderType
        cirDetailVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(cirDetailVC, animated: true)
    }
    
    // MARK:无用
    func getDateWithDateString(_ dateString: String) -> Date {
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let date = dateFormat.date(from: dateString)
        return date!
    }
}
